package com.wushixin.springdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wushixin.springdemo.pojo.Book;
import com.wushixin.springdemo.pojo.TypeInfo;
import com.wushixin.springdemo.pojo.utils.Result;
import com.wushixin.springdemo.service.TypeService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/type")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @GetMapping
    public Result GetAll() {
        return  new Result(typeService.list(),typeService.list()!=null?true:false);
    }
    @GetMapping("{id}")
    public Result GetById(@PathVariable Integer id) {
        return new Result(typeService.getById(id),true);
    }

    @PostMapping
    public Result saveStudent(@RequestBody TypeInfo type1) {
        return new Result(null,typeService.save(type1));
    }

    @DeleteMapping("{id}")
    public Result deleteStudent(@PathVariable Integer id) {
        typeService.removeWithBook(id);
        return new Result(true,"删除成功");
    }

    @PutMapping
    public Result updateStudent(@RequestBody TypeInfo type1) {
        Boolean flag = typeService.updateById(type1);

        return new Result(flag,flag?"添加成功":"添加失败");
    }

    @GetMapping("{current}/{pageSize}")
    public Result pageStudent(@PathVariable Integer current,@PathVariable Integer pageSize,String name) {
        Page<TypeInfo> typePage = new Page<TypeInfo>(current,pageSize);
        val typeLambdaQueryWrapper = new LambdaQueryWrapper<TypeInfo>();
        typeLambdaQueryWrapper.like(name!=null,TypeInfo::getName,name);
        typeService.page(typePage,typeLambdaQueryWrapper);

        if (current > typePage.getPages()) {
            typePage = new Page<>(typePage.getPages(), pageSize);
        }
        return new Result(typePage,true);
    }
}
